package core.ui;

import org.apache.log4j.Logger;

import core.descriptors.TaskDescriptor;
import core.enums.TaskTYPE;
import core.factory.WFQProxyFactory;
import core.manager.Manager;
import core.manager.Workflow;
import core.proxy.WFQueueManagerProxy;
import core.util.COREServiceRegistry;

/**
 * Oggetto che rappresenta l'interfaccia a l'interno sistema. Infatti presenta solo i metodo per creare il workflow e insererilo al sistema mediante la 
 * enqueue
 * @author Vincenzo Merlo, Scuderi Giovanni Luca, Paolo Giuffrida
 *
 */
public class UI {

    private final Logger logger = COREServiceRegistry.getLogger(UI.class.toString());
    //from class diagram
    WFQProxyFactory proxyFactory; //TODO: usare questa variabile
    WFQueueManagerProxy wfQueueManagerproxy; //TODO: usare questa variabile

    /**
     * Costruttore di default
     */
    public UI() {
        super();
    }

    /**
     * Inseriesce un workflow nella coda
     * @param workflow
     * @return
     */
    public int enqueue(Workflow workflow) {
        logger.info("enqueue " + workflow + "size " + workflow.getTasks().size());
        ((Manager) Manager.getInstance()).enqueue(workflow);
        return 0;
    }

    /**
     * Crea restituisce un workflow
     * @return
     */
    public Workflow createWorkflow() {
        logger.trace(" createWorkflow ");
        return new Workflow();
    }

    /**
     * Crea un TaskDescriptor e lo inserisce nel workflow
     * @param wf
     * @param type
     * @param command
     * @param link
     * @return 1 OK / -1 otherwise
     */
    public int addTask(Workflow wf, String type, String command, String link) {
        try {
            logger.trace(" add Task ");
            wf.addTask(crateTaskdescriptor(type, command, link));
        } catch (Exception e) {
            return -1;
        }

        return 1;
    }
    
    
    /**
     * Crea un TaskDescriptor
     * @param type
     * @param command
     * @param link
     * @return
     * @throws Exception
     */
    private TaskDescriptor crateTaskdescriptor(String type, String command, String link) throws Exception {
        logger.trace("createTaskDesccriptor");
        final TaskDescriptor td = new TaskDescriptor();
        td.setCommand(command);
        td.setLink(link);
        td.setType(TaskTYPE.valueOf(type));
        td.setID(COREServiceRegistry.getIDTaskDescriptorManager().getID()); //TODO: ...
        return td;
    }
}
